/* Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include "common.h"
#include "context_config.h"
#include "spdm_command_impl.h"
#include "component_integrity.h"

ComponentIntegrity::ComponentIntegrity() : type(""), version(""), lastUpdated(0) {}

ComponentIntegrity::ComponentIntegrity(const string& type, const string& version, uint64_t lastUpdated)
    : type(type), version(version), lastUpdated(lastUpdated), measurementSet(nullptr) {}

string ComponentIntegrity::GetType() const
{
    return type;
}

string ComponentIntegrity::GetVersion() const
{
    return version;
}

uint64_t ComponentIntegrity::GetLastUpdated()
{
    return lastUpdated;
}

void ComponentIntegrity::SetType(const string& type)
{
    this->type = type;
}

void ComponentIntegrity::SetVersion(const string& type)
{
    this->version = version;
}

void ComponentIntegrity::SetLastUpdated(uint64_t lastUpdated)
{
    this->lastUpdated = lastUpdated;
}

int32_t ComponentIntegrity::InitBaseMeasurements(void *spdm_context, uint8_t slot_id)
{
    libspdm_data_parameter_t parameter = {};
    parameter.location = LIBSPDM_DATA_LOCATION_CONNECTION;

    uint32_t hash_algo;
    size_t   hasl_algo_size = sizeof(hash_algo);

    SpdmGetData(spdm_context, LIBSPDM_DATA_BASE_HASH_ALGO, &parameter, &hash_algo, &hasl_algo_size);

    string hash_algo_str = GetCapabilityString("HashAlgo", hash_algo);
    measurementSet = new MeasurementSet(DEFAULT_SPECIFICATION, DEFAULT_SUMMARY_TPYE, hash_algo_str);

    int32_t res = measurementSet->GetMeasurementSet(spdm_context, slot_id);
    if (res != RET_OK) {
        debug_log(DLOG_ERROR, "get measurement set failed");
        return res;
    }

    res = measurementSet->GetSubMeasurements(spdm_context, hash_algo_str, slot_id);
    if (res != RET_OK) {
        debug_log(DLOG_ERROR, "get sub measurements failed");
    }

    return res;
}